package com.example.wearing.user;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.wearing.R;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class AlterPasswordActivity extends AppCompatActivity {


    private EditText oldPassword, newPassword, newPassword2;
    private Button savePasswordBtn;

    private final static String TAG = "AlterPasswordActivity";
    private int userId;
    private String userPwd;
    private Handler handler;
    private String jdbcUrl, jdbcUser, jdbcPassword;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alter_password);

        init();

        //返回
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        handler = new Handler(){
            @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
            @Override
            public void handleMessage(@NonNull Message msg){
                if(msg.what == 1){
                    Log.i(TAG, "handleMessage: 收到消息——修改用户名");
                    int res = (int) msg.obj;
                    if(res == 1){
                        //修改SharedPreferences中密码
                        SharedPreferences sp = getApplicationContext().getSharedPreferences("user", Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("user_pwd",userPwd);
                        editor.apply();
                        Toast.makeText(getApplicationContext(), "修改成功" , Toast.LENGTH_SHORT).show();
                        //返回设置界面
                        finish();
                    }else if(res == 2){
                        Toast.makeText(getApplicationContext(), "修改失败", Toast.LENGTH_SHORT).show();
                    }
                }
                super.handleMessage(msg);
            }
        };
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if(item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        super.onOptionsItemSelected(item);
        return true;
    }

    public void init(){
        oldPassword = findViewById(R.id.oldPwd);
        newPassword = findViewById(R.id.newPwd);
        newPassword2 = findViewById(R.id.newPwd2);
        savePasswordBtn = findViewById(R.id.savePwdBtn);

        //检查sharedPreference,获取用户id。密码
        SharedPreferences sp = this.getSharedPreferences("user", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        userId = sp.getInt("user_id",0);
        userPwd = sp.getString("user_pwd","");
        jdbcUrl = sp.getString("jdbc_url", "");
        jdbcUser = sp.getString("jdbc_user","");
        jdbcPassword = sp.getString("jdbc_password","");
    }

    public void savePassword(View view) {
        String oldPwd = oldPassword.getText().toString();
        String newPwd = newPassword.getText().toString();
        String newPwd2 = newPassword2.getText().toString();

        if(oldPwd.equals("")){
            Toast.makeText(getApplicationContext(), "请输入旧密码", Toast.LENGTH_SHORT).show();
        }else if(newPwd.equals("")){
            Toast.makeText(getApplicationContext(), "请输入新密码", Toast.LENGTH_SHORT).show();
        }else if(newPwd2.equals("")){
            Toast.makeText(getApplicationContext(), "请输入确认密码", Toast.LENGTH_SHORT).show();
        }else if(!oldPwd.equals(userPwd)){
            Toast.makeText(getApplicationContext(), "旧密码错误", Toast.LENGTH_SHORT).show();
        }else if(!newPwd.equals(newPwd2)){
            //判断两次密码一致
            Toast.makeText(getApplicationContext(), "两次输入密码不一致", Toast.LENGTH_LONG).show();
        }else{
            userPwd = newPwd;
            //开启线程，修改数据库password
            Thread thread = new Thread(alterPasswordRun);
            thread.start();
        }
    }

    //数据库修改用户名
    private Runnable alterPasswordRun = new Runnable() {
        @Override
        public void run() {
            //查询数据库中是否存在该用户名——存在弹窗提示
            int updateCode;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection cn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
                Statement st = (Statement)cn.createStatement();

                String updateSql = "UPDATE user set u_pwd = '"+userPwd+"' where u_id="+userId;
                int result = st.executeUpdate(updateSql);// 返回值代表收到影响的行数
                Log.i(TAG, "run: 更新数据成功" + result + "行");
                updateCode = 1;

                st.close();
                cn.close();
            } catch (ClassNotFoundException | SQLException e) {
                updateCode = 2;//出错
                Log.i(TAG, "run:SQL fail!!!__" + e);
                e.printStackTrace();
            }
            //发送消息
            Message msg = handler.obtainMessage(1, updateCode);
            handler.sendMessage(msg);
            Log.i(TAG, "run: 消息已发送---修改密码结果");

        }
    };
}